<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('biIndexData:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="10">
              <a-form-item label="省">
                <a-select
                  v-model="queryParam.proCode"
                  placeholder="请选择省份"
                  @change="
                    loadCity(),
                      (queryParam.citCode = ''),
                      (queryParam.regCode = ''),
                      (queryParam.cityName = ''),
                      (queryParam.countryName = '')
                  "
                >
                  <a-select-option value=""> 省 </a-select-option>
                  <a-select-option
                    @click="selectproname(item.name)"
                    v-for="item in ProData"
                    :key="item.areaCode"
                    :value="item.areaCode"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="10">
              <a-form-item label="市">
                <a-select
                  v-model="queryParam.citCode"
                  placeholder="请选择城市"
                  @change="loadReg(), (queryParam.regCode = ''), (queryParam.countryName = '')"
                >
                  <a-select-option value=""> 市 </a-select-option>
                  <a-select-option
                    @click="selectcityname(item.name)"
                    v-for="item in CityData"
                    :key="item.areaCode"
                    :value="item.areaCode"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="10">
              <a-form-item label="区/县">
                <a-select v-model="queryParam.regCode" placeholder="请选择区/县">
                  <a-select-option value=""> 区/县 </a-select-option>
                  <a-select-option
                    @click="selectcounname(item.name)"
                    v-for="item in RegData"
                    :key="item.areaCode"
                    :value="item.areaCode"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>

            <template v-if="advanced">
              <a-col :md="6" :sm="10">
                <a-form-item label="指标类型" has-feedback>
                  <a-tree-select
                    v-model="queryParam.typeId"
                    show-search
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择指标类型"
                    :treeData="typeTreeData"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="10">
                <a-form-item label="时间">
                  <a-select style="width: 70px; margin-right: 10px" default-value="year" v-model="timeType">
                    <a-select-option value="year"> 年份 </a-select-option>
                    <a-select-option value="month"> 月份 </a-select-option>
                    <a-select-option value="day"> 日期</a-select-option>
                  </a-select>

                  <span>
                    <a-select
                      style="width: 180px"
                      :default-value="currentYear"
                      v-model="queryParam.year"
                      v-if="timeType == 'year'"
                      placeholder="选择年份"
                    >
                      <a-select-option v-for="y in year" :key="y">
                        {{ y }}
                      </a-select-option>
                    </a-select>

                    <a-month-picker
                      @change="onChangeMonth"
                      v-if="timeType == 'month'"
                      placeholder="选择月份"
                    />
                    <a-date-picker
                      @change="onChangeDay"
                      v-if="timeType == 'day'"
                      placeholder="选择日期"
                    />
                  </span>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="10">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table ref="table" :columns="columns" :data="loadData">
        <template class="table-operator" slot="operator" v-if="hasPerm('biIndexData:add')">
          <a-button
            type="primary"
            v-if="hasPerm('timeSpaceDataRecord:add')"
            icon="plus"
            @click="$refs.uploadModal.init()">
            新增
          </a-button>
          <!-- <a-button type="primary" v-if="hasPerm('biIndexData:add')" icon="plus" @click="$refs.addForm.add()"
            >新增指标数据</a-button
          > -->
          <!-- <a-button
            type="danger"
            :disabled="selectedRowKeys.length < 1"
            v-if="hasPerm('biIndexData:delete')"
            @click="batchDelete"
            ><a-icon type="delete" />批量删除</a-button
          > -->
          <x-down v-if="hasPerm('biIndexData:export')" ref="batchExport" @batchExport="batchExport" />
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('biIndexData:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <a-divider type="vertical" v-if="hasPerm('biIndexData:edit') & hasPerm('biIndexData:delete')" />
          <!-- <a-popconfirm
            v-if="hasPerm('biIndexData:delete')"
            placement="topRight"
            title="确认删除？"
            @confirm="() => singleDelete(record)"
          >
            <a>删除</a>
          </a-popconfirm> -->
        </span>
        <!-- <span slot="timeValue" slot-scope="text, record">
          <span> {{ record.day != '' ? record.day : record.month == '' ? record.month : record.year }} </span>

        </span> -->
      </s-table>
      <add-form ref="addForm" @ok="handleOk" />
      <edit-form ref="editForm" @ok="handleOk" />
      <upload-modal ref="uploadModal" @ok="handleOk" @parseComplete="handleOk" />
    </a-card>
  </div>
</template>
<script>
import { STable, XDown } from '@/components'
import {
  biIndexDataPage,
  biIndexDataDelete,
  biIndexDataExport,
  listProvince,
  listCity,
  listRegion,
  biIndexTypeSelectTree,
} from '@/api/modular/main/biindexdata/biIndexDataManage'
import addForm from './addForm.vue'
import editForm from './editForm.vue'
import uploadModal from '@/views/main/biindexdata/modal/uploadModal'
export default {
  components: {
    STable,
    addForm,
    editForm,
    uploadModal,
    XDown
  },
  data() {
    return {
      timeType: 'year',
      year: [],
      currentYear: new Date().getFullYear(),
      minYear: 2012,
      // 指标类型list  (树)
      typeTreeData: [],
      // 省data
      ProData: {},
      // 市data
      CityData: {},
      // 区data
      RegData: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        proCode: '',
        citCode: '',
        regCode: '',
        provName: '',
        cityName: '',
        countryName: '',
        timelevel: '',
        year: '',
        month: '',
        day: ''
      },
      // 表头
      columns: [
        {
          title: '省',
          align: 'center',
          dataIndex: 'provName',
        },
        {
          title: '市',
          align: 'center',
          dataIndex: 'cityName',
        },
        {
          title: '区/县',
          align: 'center',
          dataIndex: 'countryName',
        },
        {
          title: '指标类型',
          align: 'center',
          dataIndex: 'name',
        },
        {
          title: '年',
          align: 'center',
          dataIndex: 'year',
        },
        {
          title: '月',
          align: 'center',
          dataIndex: 'month',
        },
        {
          title: '日',
          align: 'center',
          dataIndex: 'day',
        },
        {
          title: '值',
          align: 'center',
          dataIndex: 'value',
        },
      ],
      tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return biIndexDataPage(Object.assign(parameter, this.queryParam)).then((res) => {
          console.info(parameter)
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          },
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
        },
      },
    }
  },
  created() {
    // if (this.hasPerm('biIndexData:edit') || this.hasPerm('biIndexData:delete')) {
    //   this.columns.push({
    //     title: '操作',
    //     width: '150px',
    //     dataIndex: 'action',
    //     scopedSlots: { customRender: 'action' },
    //   })
    // }
    this.loadProvince()
    this.year = []
    for (let y = this.currentYear; y > this.minYear - 1; y--) {
      this.year.push(y)
    }
  },
  mounted() {
    this.loadSelectTree()
  },
  methods: {
    onChangeDay(date, dateString) {
      this.queryParam.day = dateString
      this.queryParam.month = dateString.split('-')[0]+"-"+dateString.split('-')[1]
      this.queryParam.year = dateString.split('-')[0]
    },
    onChangeMonth(date, dateString) {
      this.queryParam.month = dateString
      this.queryParam.year = dateString.split('-')[0]
    },
    // 上级父类选择器（tree）
    loadSelectTree() {
      biIndexTypeSelectTree({}).then((res) => {
        if (res.success) {
          this.typeTreeData = res.data
        }
      })
    },
    selectproname(name) {
      this.queryParam.provName = name
    },
    selectcityname(name) {
      this.queryParam.cityName = name
    },
    selectcounname(name) {
      this.queryParam.countryName = name
      console.info(this.queryParam)
    },
    /**
     * 省份查询
     */
    loadProvince() {
      const _that = this
      listProvince().then((res) => {
        if (res.success) {
          _that.ProData = res.data
        }
      })
    },
    /**
     * 市 查询
     */
    loadCity() {
      const _that = this
      listCity(this.queryParam).then((res) => {
        if (res.success) {
          _that.CityData = res.data
        }
      })
    },
    /**
     * 区/县 查询
     */
    loadReg() {
      const _that = this
      listRegion(this.queryParam).then((res) => {
        if (res.success) {
          _that.RegData = res.data
        }
      })
    },
    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ id: record.id }]
      this.biIndexDataDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { id: d }
      })
      this.biIndexDataDelete(paramIds)
    },
    biIndexDataDelete(record) {
      biIndexDataDelete(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.clearRefreshSelected()
        } else {
          this.$message.error('删除失败') // + res.message
        }
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    /**
     * 批量导出
     */
    batchExport() {
      biIndexDataExport(this.queryParam).then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
  },
}
</script>
<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
</style>
